
import Vue from 'vue';
import print from '@/api/formbase/print';
import rxAjax from '@/assets/js/ajax.js';
import {Util} from '@lowcode/jpaas-common-lib';
import FormFunctions from "@/views/modules/form/core/js-comps/FormFunctions";
import FormSolutionApi from "@/api/form/core/formSolution";
import DialogBox from "@/assets/js/DialogBox";
import FlowFunctions from "@/api/formbase/FlowFunctions";
import router from "@/router";
import NodesExecutors from "@/views/modules/bpm/core/component/NodesExecutors.vue";
import userState from "@/assets/js/userState";

export default {
    mixins:[print,FlowFunctions,userState],
    computed:{
        parentVm(){
            var vm=this;
            while (vm && !vm.rootVm){
                vm=vm.$parent;
            }
            return vm;
        },
        rxForms(){
            return this.parentVm.$refs.rxForms;
        },
        rxForm(){
            return this.parentVm.$refs.rxForm;
        },
        customForm(){
            return this.parentVm.$refs.customForm;
        },
        outSideUrlForm(){
            return this.parentVm.$refs.outSideUrlForm;
        }
    },

    methods:{
        ...FormFunctions,

        getFormData(){
            let formType=this.parentVm.processConfig.formType;
            let formData={};
            if(formType=="online") {
                if(this.rxForms){
                    formData=this.rxForms.getData();
                }else{
                    formData[this.formAlias]=this.rxForm.getData();
                }
            }else{
                formData=this.customForm.getData();
            }
            return formData;
        },

        getData(){
            var defId=this.parentVm.localDefId;
            var data={defId:defId};
            var formType=this.parentVm.processConfig.formType;
            var hasPk=this.parentVm.processConfig.hasPk;
            var formData={};
            if(formType=="online"){
                if(this.rxForms){
                    formData=this.rxForms.getData();
                }else{
                    formData[this.rxForm.formVm.alias]=this.rxForm.getData();
                }
                data.systemHand=true;
                data.hasPk=hasPk;
            }else if(formType=="custom"){
                formData=this.customForm.getData();
                data.systemHand=false;
            }else if(formType=="outsideUrl"){
                formData=this.outSideUrlForm.getData();
                data.systemHand=false;
            }
            var formJson=JSON.stringify(formData);
            data.formJson=formJson;

            let isCopy=this.parentVm.isCopy;
            if(this.parentVm.instId && !isCopy){
                data.instId=this.parentVm.instId;
            }
            data.attachment=JSON.stringify( this.parentVm.attachments);
            data.relateProcess=JSON.stringify(this.parentVm.relateProcess);
            return data;
        },
        getOpenDialogComponet(data){
            var template=`<div style="width:100%;height:100%;"> 
              <component v-if="!url" ref="current" :is="currentView" :layerid="layerid" :destroy="destroy" `;

            let ary=["currentView","url","layerid","destroy"];

            if(data) {

                for (var key in data) {
                    var value=data[key];
                    if(typeof value=='string' && value.constructor==String){
                        template += key + '="' + value + '" ';
                    }else{
                        template += ' :' + key + '="' + key + '" ';
                        ary.push( key );
                    }
                }
            }
            template +=`      ></component>
             <iframe v-else style="height:700px;width:100%;" 
                      id="iframeId" :src="url" frameborder="0" scrolling="auto"> 
              </iframe>
           </div>`;

            let aryProp=[];
            for(let key of ary){
                aryProp.push('"' + key +'"');
            }
            let props=aryProp.join(",");



            var openDialogComponet= Vue.component('open-dialog', {
                template:template,
                ...eval('({\n' +
                    '        name: "DialogView",\n' +
                    '        props:['+props+']\n' +
                    '    })')
            })
            return openDialogComponet;
        },

        /**
         * 执行表单方法。
         * @param btn
         */
        handFormMethod(btn){
            let rxForms=this.rxForms;
            let formVm;
            let method="";
            if(btn.method.indexOf(".")==-1){
                formVm=rxForms.getFormRef().formVm;
                method = btn.method;
            }
            else{
                let aryTmp=btn.method.split(".");
                let alias=aryTmp[0];
                method= aryTmp[1];
                formVm=rxForms.getFormRef(alias).formVm;
            }
            if (formVm && formVm[method]) {
                formVm[method](btn);
            }
        },
        /**
         * 处理自定义方法。
         * @param btn
         */
        handCustom(btn){
            let rxAjax = this.rxAjax;
            let formJson=this.rxForms.getData();
            let config=btn.config;
            let func=new Function("rxAjax","formJson",config.action);
            func.bind(this)(rxAjax,formJson);
        },
        /**
         * 处理pdf打印方法。
         * @param btn
         */
        handPdfPrint(btn){
            let pkId = btn.config.pkId;
            let boAlias = btn.config.boAlias;
            this.pdfPrint(pkId,boAlias,'');
        },
        /**
         * 执行按钮。
         * @param btn
         */
        handMethod(btn) {
            let rxForms=this.parentVm.$refs.rxForms;
            //表单方法
            if(btn.type=="formMethod" && rxForms){
                //执行表单方法。
                this.handFormMethod(btn);
                return;
            }
            //pdf打印
            if(btn.type=="pdfPrint"){
                //执行pdf打印方法。
                this.handPdfPrint(btn);
                return;
            }
            //自定义方法
            if(btn.type=="custom"){
                this.handCustom(btn);
                return;
            }
            //调用预定义方法。
            this[btn.method](btn);
        },
        /**
         * 打开列表
         * @param btn
         */
        openBpmListDialog(btn){
            if (!btn.config){
                this.$message.warning(this.$ti18('msa.noList',"未配置列表","bpmTask"));
                return;
            }
            if (!btn.config.listConfig){
                this.$message.warning(this.$ti18('msa.noList',"未配置列表","bpmTask"));
                return;
            }
            var config=JSON.parse(btn.config.listConfig)
            var listConf = {
                curVm:this,
                max:config.isMax == "YES" ? true : false,
                shade:config.model,
            }
            if(config.isMax == "NO"){
                listConf["widthHeight"] = [listConfig.width + 'px', listConfig.height + 'px']
            }
            var fieldALlMap=JSON.parse(config.fieldMap);
            //筛选出使用表单字段映射的参数
            // 获取表单数据
            var formData=this.rxForms.getData();
            var allData={}
            for (let data in formData){
                Object.assign(allData,formData[data])
            }
            //var fieldMap=fieldALlMap.filter(item=>item.valueType=="field")
            var queryParams=[]
            var typeJson = {string: "S", int: "I", date: "D", float: "F"};
            if (fieldALlMap.length>0 ){
                for (let param of fieldALlMap){
                    let valType=param.valueType
                    var tablePre = param.tablePre ? param.tablePre + "." : "";
                    var type = typeJson[param.dataType] ? typeJson[param.dataType] : "S";
                    var queryString = "Q_" + tablePre + param.destField + "_" + type + "_" + param.fieldOp;
                    var tmp = ""
                    if (valType == "curUserId") {
                        tmp=queryString + "=" + this.user.userId;
                    } else if (valType == "curDeptId") {
                        tmp=queryString + "=" + this.user.deptId;
                    }else if (valType=="curName"){
                        tmp=queryString + "=" + this.user.fullName;
                    }else if (valType=="curTenantId"){
                        tmp=queryString + "=" + this.user.tenantId;
                    }else if (valType=="curUserAccount"){
                        tmp=queryString + "=" + this.user.account;
                    } else if (valType == "curdeptName") {
                        tmp=queryString + "=" + this.user.deptName;
                    } else if (valType == "curCompanyId") {
                        tmp=queryString + "=" + this.user.companyId;
                    } else if (valType == "field"){
                        let srcField=param.srcField.toLowerCase();
                        if(!srcField){
                            continue;
                        }
                        if (!allData[srcField]){
                            continue;
                        }
                        tmp=queryString + "=" + allData[srcField];
                    }

                    queryParams.push(tmp);
                }
            }

            DialogBox.dialog({key:config.alias,params:queryParams.join("&")},{...listConf},function (action,data) {});

        },
        /**
         * 打开表单。
         * @param btn
         */
        openSolutionForm(btn) {
            let self_ = this;
            let formJson = {};
            let config=btn.config;
            let rxForms;
            if(this.rxForms){
                rxForms = this.rxForms;
            }
            let formVm= rxForms.getFormRef().formVm;
            formJson[formVm.alias] = rxForms.getData();
            let data=formJson[formVm.alias];
            let dataDetail = data[formVm.alias];
            let initData=this.getInitData(config,dataDetail);
            DialogBox.showForm({
                title: config.formName,
                curVm: self_,
                data: {
                    alias: config.formAlias, setInitData: function (data) {
                        return Object.assign(data, initData);
                    },
                    closeOnSave:true
                },
                max: true
            }, function (action,data) {
                if(formVm[config.callback]){
                    formVm[config.callback](action,data);
                }
            });
        },
        //获取打开表单的初始化数据
        getInitData(config,data){
            let formData={};
            //根据配置 构建映射数据
            if(config.formConfig){
                let formConfig=JSON.parse(config.formConfig);
                for (let i = 0; i < formConfig.length; i++) {
                    let obj=formConfig[i];
                    if(!obj.fieldConfig || obj.fieldConfig.length==0){
                        continue;
                    }
                    for (let j = 0; j < obj.fieldConfig.length; j++) {
                        let fieldConfig=obj.fieldConfig[j];
                        //映射到主表
                        if(obj.targetType=="main"){
                            //当前主表
                            if(fieldConfig.curType=="main"){
                                formData[fieldConfig.targetField]=data[fieldConfig.curField];
                            }else  if(fieldConfig.curType=="onetoone"){ //当前一对一子表
                                formData[fieldConfig.targetField]=data["sub__"+fieldConfig.curTable][fieldConfig.curField];
                            }
                        }else if(obj.targetType=="onetoone"){//映射到一对一子表
                            //一对一子表无数据时默认{}
                            if(!formData["sub__"+obj.targetTable]){
                                formData["sub__"+obj.targetTable]={};
                            }
                            //当前主表
                            if(fieldConfig.curType=="main"){
                                formData["sub__"+obj.targetTable][fieldConfig.targetField]=data[fieldConfig.curField];
                            }else  if(fieldConfig.curType=="onetoone"){ //当前一对一子表
                                formData["sub__"+obj.targetTable][fieldConfig.targetField]=data["sub__"+fieldConfig.curTable][fieldConfig.curField];
                            }
                        }else if(obj.targetType=="onetomany") {//映射到一对多子表
                            if(!formData["sub__"+obj.targetTable]){
                                formData["sub__"+obj.targetTable]=[];
                            }
                            if(!formData.initData){
                                formData.initData={}
                            }
                            //子表一行的初始化数据
                            if(!formData.initData[obj.targetTable]){
                                formData.initData[obj.targetTable]={};
                            }
                            //当前主表
                            if(fieldConfig.curType=="main"){
                                formData.initData[obj.targetTable][fieldConfig.targetField]=data[fieldConfig.curField];
                                if(formData["sub__"+obj.targetTable] && formData["sub__"+obj.targetTable].length>0){
                                    for (let k = 0; k < formData["sub__"+obj.targetTable].length; k++) {
                                        formData["sub__"+obj.targetTable][k][[fieldConfig.targetField]]=data[fieldConfig.curField];
                                    }
                                }
                            }else  if(fieldConfig.curType=="onetoone"){ //当前一对一子表
                                formData.initData[obj.targetTable][fieldConfig.targetField]=data["sub__"+fieldConfig.curTable][fieldConfig.curField];
                                if(formData["sub__"+obj.targetTable] && formData["sub__"+obj.targetTable].length>0){
                                    for (let k = 0; k < formData["sub__"+obj.targetTable].length; k++) {
                                        formData["sub__"+obj.targetTable][k][[fieldConfig.targetField]]=data["sub__"+fieldConfig.curTable][fieldConfig.curField];
                                    }
                                }
                            }else {//当前一对多子表
                                if(!data["sub__"+fieldConfig.curTable]){
                                    continue;
                                }
                                for (let k = 0; k < data["sub__"+fieldConfig.curTable].length; k++) {
                                    let row=data["sub__"+fieldConfig.curTable][k];
                                    //一对多子表单行无数据时默认{}
                                    if(!formData["sub__"+obj.targetTable][k]){
                                        let subRow=JSON.parse(JSON.stringify(formData.initData[obj.targetTable]));
                                        subRow[fieldConfig.targetField]= row[fieldConfig.curField];
                                        formData["sub__"+obj.targetTable][k]=subRow;
                                    }else {
                                        formData["sub__"+obj.targetTable][k][fieldConfig.targetField]=row[fieldConfig.curField];
                                    }
                                }
                            }
                        }
                    }
                }
            }
            return formData;
        },


        /**
         * 打开自定义表单。
         * @param btn
         */
        openCustomForm(btn) {
            let self_ = this;
            let config=btn.config;
            let rxForms=this.parentVm.$refs.rxForms;
            let formJson = rxForms.getData();
            FormSolutionApi.getValueByCustomFormConfig({
                formJson: formJson,
                formConfig: config.formConfig || []
            }).then(res => {
                DialogBox.showForm({
                    title: config.formName,
                    curVm: self_,
                    data: {
                        alias: config.formAlias, setInitData: function (data) {
                            return Object.assign(data, res);
                        },
                        closeOnSave:true
                    },
                    max: true
                }, function (action,data) {
                    if(config.script){
                        let rxAjax = self_.rxAjax;
                        let formJson=self_.rxForms.getData();
                        let func=new Function("rxAjax","formJson","action","data", config.script);
                        func.bind(self_)(rxAjax,formJson,action,data);
                    }
                });
            })
        },



        goBack(){
            router.back()
        },
        //特送按钮
        specialDelivery(btn){
            let self=this;
            let formJson =this.getFormJson();
            Util.open({
                component:NodesExecutors,
                curVm:this,
                widthHeight:['800px','550px'],
                title: this.$ti18('taskExecutors.exePath',"特送","bpmTask"),
                data:{
                    formData:JSON.parse(formJson),
                    bpmTask:this.bpmTaskDetail.bpmTask,
                    processConfig:this.bpmTaskDetail.processConfig,
                    taskConfig:this.bpmTaskDetail.taskConfig
                }
            },function (action,data){
                if(action!='ok'){
                    return;
                }
                var reg = /(taskId=[^&]*)(&{0,1})/m;
                let href=location.href.replace(reg,function (){
                    return "";
                });
                if(href.indexOf("?")==-1){
                    href+="?time=" + new Date().getTime();
                }
                else {
                    href+="&time=" + new Date().getTime();
                }

                location.href=href;
            });
        }
    }
}